package com.unicom.office.impl;

import com.unicom.office.config.OfficeConfig;
import com.unicom.office.node.*;
import com.unicom.office.parser.ExcelParser;
import com.unicom.office.parser.OfficeSyntaxParser;
import com.unicom.office.runtime.OfficeRuntime;

import java.io.BufferedReader;
import java.io.FileReader;

public class CSVParser extends ExcelParser {
    public CSVParser(){
        super(null, null);
    }

    public CSVParser(OfficeConfig config, OfficeRuntime runtime) {
        super(config, runtime);
    }

    protected WorkbookNode parseWorkbook(Object source) {
        WorkbookNode workbookNode = new WorkbookNode(null);
        parseWorksheet(source, workbookNode);
        return workbookNode;
    }

    protected WorksheetNode parseWorksheet(Object source, OfficeNode parentNode) {
        WorksheetNode worksheetNode = new WorksheetNode(null);
        parentNode.addChild(worksheetNode);
        String[] rows = source.toString().split("\\r\\n");
        for (String row : rows) {
            parseRow(row, worksheetNode);
        }
        return worksheetNode;
    }

    public Object getSource(String sourcePath) {
        try{
            BufferedReader bufferedReader = new BufferedReader(new FileReader(sourcePath));
            StringBuffer stringBuffer = new StringBuffer();
            String temp = null;
            while ((temp = bufferedReader.readLine()) != null){
                if(stringBuffer.length() > 0) {
                    stringBuffer.append("\r\n");
                }
                stringBuffer.append(temp);
            }
            return stringBuffer.toString();
        }catch(Exception ex){
            throw new RuntimeException(ex.getMessage());
        }
    }

    protected OfficeNodeType parseType(Object source) {
        return OfficeNodeType.Workbook;
    }

    protected TextboxNode parseTextbox(Object source, OfficeNode parentNode) {
        return null;
    }

    protected RowNode parseRow(Object source, OfficeNode parentNode) {
        RowNode rowNode = new RowNode(null);
        parentNode.addChild(rowNode);
        String[] cells = source.toString().split("\\,");
        for (String cell : cells) {
            parseCell(cell, rowNode);
        }
        return rowNode;
    }

    protected CellNode parseCell(Object source, OfficeNode parentNode) {
        CellNode cellNode = new CellNode(null);
        parentNode.addChild(cellNode);
        cellNode.setText(source.toString(), false);
        // 开始语法解析
        OfficeSyntaxParser syntaxParser = new OfficeSyntaxParser(cellNode.getFirstParagraphNode(), config);
        syntaxParser.parse();
        return cellNode;
    }

    protected ParagraphNode parseParagraph(Object source, OfficeNode parentNode) {
        return null;
    }

    protected TextRangeNode parseTextRange(Object source, OfficeNode parentNode) {
        return null;
    }

    protected PictureNode parsePicture(Object source, OfficeNode parentNode) {
        return null;
    }
}
